package com.heima.behavlor.service.impl;
import java.util.Date;
import java.util.Queue;

import com.heima.behavlor.service.ApBehaviorEntryService;
import com.heima.behavlor.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.wemedia.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @package com.heima.behavlor.service.impl
 * @Date 2022/3/8
 * @project heima-leadnews
 */
@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 点赞和取消点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user.getId()==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 根据当前登录用户id查询行为实体对象
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);

        // 3. 如果是点赞操作  判断是否已经点过赞
        if (dto.getOperation()==0){

            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
            ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
            if (apLikesBehavior!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"已经点过赞了，不要重复点赞");
            }
            // 4. 没有点过赞则 像mongo点赞集合中 添加点赞数据
            ApLikesBehavior apLikesBehaviorIn = new ApLikesBehavior();
            apLikesBehaviorIn.setEntryId(apBehaviorEntry.getId());
            apLikesBehaviorIn.setArticleId(dto.getArticleId());
            apLikesBehaviorIn.setType((short)0);
            apLikesBehaviorIn.setOperation(dto.getOperation());
            apLikesBehaviorIn.setCreatedTime(new Date());
            mongoTemplate.save(apLikesBehaviorIn);

        }else {
            // 5. 如果是取消点赞操作  在mongo点赞集合中 删除对应点赞数据
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
            mongoTemplate.remove(query,ApLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
